/*
 * UserServiceImpl.java
 * Copyright 2018 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package com.bearox.trans.service.impl;

import com.bearox.trans.data.domain.User;
import com.bearox.trans.data.dto.UserDto;
import com.bearox.trans.mapper.UserMapper;
import com.bearox.trans.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Bearox
 */
@Service
public class UserServiceImpl implements UserService {

    private static final BCryptPasswordEncoder CRYPT_PASSWORD_ENCODER =
            new BCryptPasswordEncoder();

    private final UserMapper userMapper;

    public UserServiceImpl(final UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Long register(final UserDto userDto, final String password) {
        if (!checkUser(userDto) || password == null) {
            return null;
        }
        final User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setPassword(CRYPT_PASSWORD_ENCODER.encode(password));
        user.setUserName(userDto.getName());
        if (userMapper.register(user) > 0) {
            return user.getId();
        }
        return null;
    }

    private boolean checkUser(final UserDto userDto) {
        return null != userDto && userDto.getName() != null && userDto.getTelephone() != null
                && userDto.getType() != null && userMapper.getUserByName(userDto.getName()) == null;
    }
}
